#include "sqplus.h"
#include <stdio.h>

using namespace SqPlus;

#pragma comment (lib, "../lib/squirrelD.lib")
#pragma comment (lib, "../lib/sqstdlibD.lib")
#pragma comment (lib, "../lib/sqplusD.lib")


class CLocation
{
public:
	int x, y, radius;

	char *name;
};


class CTestManager
{
private:
	CLocation* m_location[10];
	int m_count;

	CTestManager()
	{
		m_count = 0;
		printf("Created testManager\n");
	}

	static CTestManager *_this;
public:
	static CTestManager *getInstance()
	{
		if (!_this)
			_this = new CTestManager();
		return _this;
	}

	CLocation* addLocation(const SQChar *name, int x, int y, int radius, const SQChar *script)
	{
		printf("Adding location\n");
		CLocation *loc = new CLocation();
		loc->x = x;
		loc->y = y;
		loc->radius = radius;
		loc->name = new char[strlen(name)+1];
		strcpy(loc->name, name);

		char tmp[1024];

		sprintf(tmp, "function tmp_%s(_this) {\n%s\n}", name, script);
		SquirrelVM::RunScript(SquirrelVM::CompileBuffer(tmp));
		
		m_location[m_count++] = loc;
		return loc;
	}

	void update()
	{
		printf("Updating %d tests...\n",m_count);
		for (int i=0;i<m_count;i++)
		{
			char tmp[100];
			sprintf(tmp,"tmp_%s", m_location[i]->name);
			SquirrelFunction<void> sf = SquirrelFunction<void>(tmp);

			sf(m_location[i]);
		}
	};
};

CTestManager *CTestManager::_this = NULL;

DECLARE_INSTANCE_TYPE(CLocation);
DECLARE_INSTANCE_TYPE(CTestManager);

bool runScript(char *path)
{
	FILE *f = fopen(path, "rb");
	if (!f)
		return FALSE;

	fseek(f, 0, SEEK_END);
	long len = ftell(f);
	fseek(f,0,SEEK_SET);

	char *tmp = new char[len+1];
	fread(tmp, len, 1, f);
	fclose(f);

	tmp[len] = 0;

	SquirrelObject obj = SquirrelVM::CompileBuffer(tmp);
	SquirrelVM::RunScript(obj);

	delete[] tmp;

	return TRUE;
}

int main(int argc,char * argv[]) 
{
	SquirrelVM::Init();

	SQClassDef<CLocation>("CLocation")
		.var(&CLocation::x, "x")
		.var(&CLocation::y, "y")
		.var(&CLocation::radius, "radius");


	SQClassDefNoConstructor<CTestManager>("CTestManager")
		.staticFunc(&CTestManager::getInstance, "getInstance")
		.func(&CTestManager::addLocation, "addLocation")
		.func(&CTestManager::update, "update");

	runScript("../src/test.nut");


	CTestManager::getInstance()->addLocation("t1", 100, 100, 10, "print(\"Here is 1 at (\"+_this.x+\", \"+_this.y+\")\")");
	CTestManager::getInstance()->addLocation("t2", 5, 20, 10, "print(\"Here is 2\")");
	CTestManager::getInstance()->addLocation("t3", 0, 0, 10, "_this.x = _this.y = -1; print(\"I'm here now!\");");

	CTestManager::getInstance()->update();

	SquirrelVM::Shutdown();
}